<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Chat</title>


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body onload="init()">
<script>
	var target = "{{target}}"

	function init() {	
		scrollToBottom("chat-list");
		resetTimer();
	}

	var timer;
	function resetTimer() {
		timer = setTimeout("checkForMessages()", 4*1000);
	}

	function send(){
		var xmlHttp = null;
	    	xmlHttp = new XMLHttpRequest();
	    	xmlHttp.open( "POST", '/sendMessage/'+target+'/', false );
		var params = "text="+document.getElementById("text").value;
		document.getElementById("text").value = "";
		//alert(params);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
	    	xmlHttp.send( params );
		var response = String(xmlHttp.responseText);
		document.getElementById("chat-list").innerHTML += response;
		scrollToBottom("chat-list");
	}

	function checkForMessages() {
		var xmlHttp = null;
	    	xmlHttp = new XMLHttpRequest();
	    	xmlHttp.open( "GET", '/newMessages/'+target+'/', false );
		xmlHttp.setRequestHeader("Connection", "close");
	    	xmlHttp.send( null );
		var response = String(xmlHttp.responseText);
		document.getElementById("chat-list").innerHTML += response;
		scrollToBottom("chat-list");
		resetTimer();
	}

	function scrollToBottom(id){
		document.getElementById(id).scrollTop=document.getElementById(id).scrollHeight
	} 
</script>
<header  id="Menu" style="width:100%; height:25px;margin-top:4px;">
<div>
	<input type="submit" value="Map" id="Map"  name="Map" style="width:75px;height:25px" onclick="window.location='/'"/>
	<input type="submit" value="Friends" id="Friends"  name="Friends" style="width:75px;height:25px" onclick="window.location='/friends/'"/>
	<input type="submit" value="Inbox" id="Inbox" name="Inbox" style="width:75px;height:25px" onclick="window.location='/inbox/'"/>
	<input type="submit" value="Everybody" id="Everybody"  name="Everybody" style="width:75px;height:25px" onclick="window.location='/everybody/'"/>
	<input type="submit" value="Logout" id="Logout"  name="Logout" style="width:75px;height:25px" onclick="window.location='/logout/'"/>
</div>
</header>
<a href="/map/{{target}}">
<p><strong>
{{ target }}
</strong></p>
</a>
<div id="chat-list" style="height:200px; width:400px; overflow:auto">
{% for msg in messages %}
{{ msg.source }} ({{ msg.timestamp }}): {{ msg.text }}<br/>
{% endfor %}
</div>
<div id="input">
<input type="text" id="text" name="text" onkeydown="if (event.keyCode == 13) send()"/><input type="submit" id="sendButton" value="Send" onclick="send()"/>
</div>
<div id="refreshResponse" style="width:100%; height:100%" color="#FFFFFF"></div>

</body>
</html>
